import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    AsyncStorage,
    DeviceEventEmitter,
    StatusBar,
    Platform
} from 'react-native';
import {ListRow, SearchInput,Drawer,Theme} from 'teaset';
import Config from '../../common/Config'
import Utils from '../../common/Utils'
import {Toast,ModalIndicator} from 'teaset';
const {height, width} = Dimensions.get('window');
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
export default class BackUpDetailsPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
        this.msgListener = DeviceEventEmitter.addListener('refresh',(listenerMsg) => {
            this.getInfo()
        });
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
            "type":"laolai"
        };
        fetch(Config.baseApi+'/user/getReference',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                if(responseJson.status!==1){
                    let ds=new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2,});
                    if(responseJson.data.length>0){
                        this.setState({
                            isHave:true,
                            dataSource:ds.cloneWithRows(responseJson.data)
                        })
                    }else {
                        this.setState({
                            isHave:false
                        })
                    }
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    componentWillUnmount() {
        this.msgListener&&this.msgListener.remove();
    }

    constructor(props) {
        super(props);
        this.state = {
            token:'',
            isHave:false,
            dataSource: new ListView.DataSource({
                rowHasChanged: (r1, r2) => r1 !== r2,
            }),
            searchMsg:''
        }
    };

    _navigator=(navView)=> {
        let _this=this;
        return (
            <View>
                <View style={styles.navigationView}>
                    {navView}
                </View>
            </View>
        )
    };

    refresh=()=>{
        if(this.state.searchMsg!==''){
            let params={
                "token":this.state.token,
                "type":"laolai",
                "content":this.state.searchMsg
            };
            fetch(Config.baseApi+'/lending/search',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: Utils.getParamsString(params)
            })
                .then((response) => response.json())
                .then((responseJson) => {
                    ModalIndicator.hide();
                    if(responseJson.status!==1){
                        let ds=new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2,});
                        if(responseJson.data.length>0){
                            this.setState({
                                isHave:true,
                                dataSource:ds.cloneWithRows(responseJson.data)
                            })
                        }else {
                            this.setState({
                                dataSource:new ListView.DataSource({
                                    rowHasChanged: (r1, r2) => r1 !== r2,
                                }),
                            });
                            Toast.message('没有这条记录')
                        }
                    }else{
                        Toast.message(responseJson.msg);
                    }
                })
                .catch((error) => {
                    ModalIndicator.hide();
                    Toast.message(error);
                });
        }else {
            this.getInfo()
        }
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor='white'
                    barStyle={'dark-content'}/>
                {this.state.isHave
                    ?(<View style={{flex:1}}>
                        <View style={styles.searchInputView}>
                            <SearchInput
                                autoCapitalize={'none'}
                                style={styles.searchInput}
                                placeholder='搜索'
                                onChangeText={(text)=>{
                                    this.setState({
                                        searchMsg:text,
                                    },()=>this.refresh())
                                }}
                                clearButtonMode='while-editing'/>
                        </View>
                        <ListView dataSource={this.state.dataSource}
                                  renderRow={(rowData,sectionID,rowID) => this.renderItem(rowData,sectionID,rowID)}
                                  removeClippedSubviews={false}
                                  showsVerticalScrollIndicator={false}/>
                    </View>)
                :(<View style={{width:width,alignItems:'center'}}>
                        <Image
                            source={ImageUtil.EnquiriesBackground}
                            style={styles.backgroundImg}/>
                        <Text style={styles.backgroundMsg}>暂时没有备档</Text>
                        <TouchableOpacity
                            onPress={()=>Actions.ArrearsModifyInformationPage()}
                            style={styles.ButView}>
                            <Text style={styles.ButMsg}>上传老赖</Text>
                        </TouchableOpacity>
                    </View>)}
            </View>
        );
    }
    renderItem=(rowData,sectionID,rowID)=>{
        return(
            <View>
                <TouchableOpacity
                    onPress={()=>Actions.ArrearsDetailedInformationPage({id:rowData.id})}
                    style={styles.labelView}>
                    <View style={{flexDirection:'row',marginTop:14}}>
                        <Text style={{marginLeft:15,color:'#3090dd',fontSize:14}}>{parseInt(rowID)+1}</Text>
                        <Text style={{color:'#3090dd',fontSize:14,marginLeft:13}}>{rowData.name}</Text>
                    </View>
                    <View style={{flexDirection:'row',marginTop:10,alignItems:'center'}}>
                        <Text style={styles.labelLeftMsg}>身份证号</Text>
                        <Text style={{marginLeft:5,fontSize:14}}>：</Text>
                        <Text sgtyle={styles.labelRightMsg}>{rowData.idCard}</Text>
                    </View>
                    <View style={{flexDirection:'row',marginTop:10,alignItems:'center'}}>
                        <Text style={styles.labelLeftMsg}>借款日期</Text>
                        <Text style={{marginLeft:5,fontSize:14,textAlign:'center',}}>：</Text>
                        <Text sgtyle={styles.labelRightMsg}>{rowData.borrowingTimeStr}</Text>
                        <Text style={[styles.labelLeftMsg,{marginLeft:18}]}>借款金额</Text>
                        <Text style={{marginLeft:5,fontSize:14,textAlign:'center',}}>：</Text>
                        <Text sgtyle={styles.labelRightMsg}>{rowData.borrowingMoney}</Text>
                    </View>
                    <View style={{flexDirection:'row',marginTop:10,alignItems:'center'}}>
                        <Text style={styles.labelLeftMsg}>还款日期</Text>
                        <Text style={{marginLeft:5,fontSize:14,textAlign:'center',}}>：</Text>
                        <Text sgtyle={styles.labelRightMsg}>{rowData.repaymentTimeStr}</Text>
                        <Text style={[styles.labelLeftMsg,{marginLeft:17}]}>还款金额</Text>
                        <Text style={{marginLeft:5,fontSize:14,textAlign:'center',}}>：</Text>
                        <Text sgtyle={styles.labelRightMsg}>{rowData.repaymentMoney}</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    };
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#ffffff',
        width:width,
        alignItems:'center',
        justifyContent:'center',
        height:Platform.OS==='ios'?64:44,
        borderBottomWidth:1,
        borderColor:'#e4e4e4'
    },
    titleMsg:{
        fontSize:17,
        color:'#000000',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    goBackView:{
        position: 'absolute',
        top:Platform.OS==='ios'?65/2:25/2,left:15,
    },
    goBackImg:{
        height:18,
        width:18
    },
    completeView:{
        position: 'absolute',
        right:15,top:Platform.OS==='ios'?65/2:10
    },
    completeMsg:{
        color:'#3090dd',
        fontSize:17
    },
    searchInputView:{
        marginTop:12,
        alignItems:'center'
    },
    searchInput:{
        width:width-30,
        height:29,
        borderWidth:1,
        borderColor:'#e3e3e4',
        marginBottom:2
    },
    labelView:{
        width:width,
        height:127,
        backgroundColor:'#ffffff',
        marginTop:10,
        borderColor:'#e4e4e4',
        borderBottomWidth:1,
        borderTopWidth:1
    },
    labelLeftMsg:{
        marginLeft:34,
        fontSize:14,
        textAlign:'center',
    },
    labelRightMsg:{
        marginLeft:7,
        fontSize:14,
        textAlign:'center',
    },
    backgroundImg:{
        marginTop:112,
        height:185,
        width:185,
        resizeMode: Image.resizeMode.stretch,
    },
    backgroundMsg:{
        marginTop:14,
        fontSize:17,
        color:'#646464',
        opacity:0.5
    },
    ButView:{
        height:34,
        width:99,
        borderColor:'#3090dd',
        borderWidth:1,
        borderRadius:5,
        justifyContent:'center',
        alignItems:'center',
        marginTop:20
    },
    ButMsg:{
        fontSize:15,
        color:'#3090dd',
        textAlign:'center'
    },
    navigationView:{
        height:64,
        width:width,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#6590ff',
        paddingTop:15
    },
    mainView:{
        flex:1,
    },

});
